package com.mcxx.modules.temporary.service.impl;

import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import com.alibaba.fastjson.JSONObject;
import com.mcxx.common.exception.BizException;
import com.mcxx.constant.DictConstant;
import com.mcxx.constant.MQConstant;
import com.mcxx.convert.ActivitiConvert;
import com.mcxx.convert.OrderConvert;
import com.mcxx.convert.TmpBankInfoConvert;
import com.mcxx.easyrule.template.RuleEngineTemplate;
import com.mcxx.modules.minimumliving.service.ScheduleCheckService;
import com.mcxx.modules.temporary.service.TempBackLogService;
import com.mcxx.modules.temporary.service.TempSalvationApplyService;
import com.mcxx.modules.base.service.read.ActivitiReadService;
import com.mcxx.modules.base.service.read.DictionaryReadService;
import com.mcxx.modules.base.service.read.RuleEngineReadService;
import com.mcxx.modules.base.utils.QueryParamUtil;
import com.mcxx.modules.filemanage.easypoi.util.ExportExcelService;
import com.mcxx.modules.filemanage.file.service.FileService;
import com.mcxx.modules.miniSalvation.check.entity.CheckEntity;
import com.mcxx.modules.miniSalvation.check.service.read.CheckReadService;
import com.mcxx.modules.miniSalvation.check.service.write.CheckWriteService;
import com.mcxx.modules.miniSalvation.family.dto.FamilyMainHistoryDTO;
import com.mcxx.modules.miniSalvation.family.entity.BankEntity;
import com.mcxx.modules.miniSalvation.family.service.read.BankReadService;
import com.mcxx.modules.miniSalvation.family.service.read.FamilyMainHistoryReadService;
import com.mcxx.modules.miniSalvation.family.service.write.BankWriteService;
import com.mcxx.modules.miniSalvation.order.dao.read.StandardReadDao;
import com.mcxx.modules.miniSalvation.order.dto.CheckDTO;
import com.mcxx.modules.miniSalvation.order.dto.OrderInHouseDTO;
import com.mcxx.modules.miniSalvation.order.entity.OrderStateEntity;
import com.mcxx.modules.miniSalvation.order.param.ActivitiParam;
import com.mcxx.modules.miniSalvation.order.param.OrderBizStateParam;
import com.mcxx.modules.miniSalvation.order.param.ReferenceParam;
import com.mcxx.modules.miniSalvation.order.service.read.InHouseReadService;
import com.mcxx.modules.miniSalvation.order.service.write.InHouseWriteService;
import com.mcxx.modules.temporary.family.dto.TemMemberAndSalaryDTO;
import com.mcxx.modules.temporary.family.dto.TmpFamilyMemberDTO;
import com.mcxx.modules.temporary.family.entity.TmpFamilyMainEntity;
import com.mcxx.modules.temporary.family.entity.TmpFamilyMemberEntity;
import com.mcxx.modules.temporary.family.service.read.TmpFamilyMainReadService;
import com.mcxx.modules.temporary.family.service.read.TmpFamilyMemberReadService;
import com.mcxx.modules.temporary.family.service.write.TmpFamilyMainHistoryWriteService;
import com.mcxx.modules.temporary.family.service.write.TmpFamilyMainWriteService;
import com.mcxx.modules.temporary.family.service.write.TmpFamilyMemberWriteService;
import com.mcxx.modules.temporary.order.dto.*;
import com.mcxx.modules.temporary.order.entity.TmpOrderDetailEntity;
import com.mcxx.modules.temporary.order.entity.TmpOrderEntity;
import com.mcxx.modules.temporary.order.param.TemporaryOrderParam;
import com.mcxx.modules.temporary.order.service.read.TmpOrderCertReadService;
import com.mcxx.modules.temporary.order.service.read.TmpOrderDetailReadService;
import com.mcxx.modules.temporary.order.service.read.TmpOrderReadService;
import com.mcxx.modules.temporary.order.service.write.TmpOrderDetailWriteService;
import com.mcxx.modules.temporary.order.service.write.TmpOrderWriteService;
import com.mcxx.modules.temporary.salary.entity.TmpFamilySalaryEntity;
import com.mcxx.modules.temporary.salary.entity.TmpMemberSalaryEntity;
import com.mcxx.modules.temporary.salary.service.read.TmpFamilySalaryReadService;
import com.mcxx.modules.temporary.salary.service.read.TmpMemberSalaryReadService;
import com.mcxx.modules.temporary.salary.service.write.TmpFamilySalaryWriteService;
import com.mcxx.modules.temporary.salary.service.write.TmpMemberSalaryWriteService;
import com.mcxx.result.BaseResult;
import com.mcxx.util.BatchNoUtil;
import com.mcxx.util.CommonUtil;
import com.mcxx.util.Constant;
import com.mcxx.util.FailureCode;
import com.yinhai.ta404.component.audit.vo.ExcelInfo;
import com.yinhai.ta404.core.security.vo.UserAccountVo;
import com.yinhai.ta404.core.service.BaseService;
import com.yinhai.ta404.core.transaction.annotation.TaTransactional;
import com.yinhai.ta404.module.dict.entity.TaDictPo;
import org.apache.commons.collections4.CollectionUtils;
import org.jeasy.rules.api.Facts;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

@Service("tempBackLogService")
@TaTransactional
public class TempBackLogServiceImpl extends BaseService implements TempBackLogService {

    private final static Logger log = LoggerFactory.getLogger(TempBackLogServiceImpl.class);

    @Autowired
    private TmpFamilyMemberReadService tmpFamilyMemberReadService;
    @Autowired
    private TmpOrderCertReadService tmpOrderCertReadService;
    @Autowired
    private CheckWriteService checkWriteService;
    @Autowired
    private TmpOrderReadService tmpOrderReadService;
    @Autowired
    private TmpOrderWriteService tmpOrderWriteService;
    @Autowired
    private InHouseWriteService inHouseWriteService;
    @Autowired
    private TmpFamilySalaryWriteService tmpFamilySalaryWriteService;
    @Autowired
    private TmpMemberSalaryWriteService tmpMemberSalaryWriteService;
    @Autowired
    private TmpFamilySalaryReadService tmpFamilySalaryReadService;
    @Autowired
    private TmpOrderDetailWriteService tmpOrderDetailWriteService;
    @Autowired
    private RuleEngineTemplate ruleEngineTemplate;
    @Autowired
    private FamilyMainHistoryReadService familyMainHistoryReadService;
    @Autowired
    private CheckReadService checkReadService;
    @Autowired
    private TmpFamilyMemberWriteService tmpFamilyMemberWriteService;
    @Autowired
    private ActivitiReadService activitiReadService;
    @Autowired
    private InHouseReadService inHouseReadService;
    @Autowired
    private TmpMemberSalaryReadService tmpMemberSalaryReadService;
    @Autowired
    private TmpFamilyMainWriteService tmpFamilyMainWriteService;
    @Autowired
    private DictionaryReadService dictionaryReadService;
    @Autowired
    private BankWriteService bankWriteService;
    @Autowired
    private TmpFamilyMainReadService tmpFamilyMainReadService;
    @Autowired
    private ScheduleCheckService scheduleCheckService;
    @Autowired
    private TempSalvationApplyService tempSalvationApplyService;
    @Autowired
    private RuleEngineReadService ruleEngineReadService;
    @Autowired
    private TmpOrderDetailReadService tmpOrderDetailReadService;
    @Autowired
    private FileService fileService;
    @Autowired
    private TmpFamilyMainHistoryWriteService tmpFamilyMainHistoryWriteService;
    @Autowired
    private StandardReadDao standardReadDao;
    @Autowired
    private BankReadService bankReadService;
    @Resource
    private ExportExcelService exportExcelService;
    @Autowired
    private RabbitTemplate rabbitTemplate;


    @Override
    public Map<String, List<String>> sendCheck(List<CheckDTO> checkList, UserAccountVo userAccountVo, String businessType) {
        Map<String, List<String>> idcardCheckRstMsg = new HashMap<>();

        List<String> familyIds =  this.verifyInfComp(checkList,idcardCheckRstMsg);

        checkList = checkList.stream().filter(c->familyIds.contains(c.getFamilyId())).collect(Collectors.toList());
        if(CollectionUtils.isEmpty(checkList)){
            return idcardCheckRstMsg;
        }

        this.verifyNoCompleteCheck(checkList,idcardCheckRstMsg);
        if(CollectionUtils.isEmpty(checkList)){
            return idcardCheckRstMsg;
        }

        log.info("开始保存数据到check表");
        checkWriteService.addCheck(checkList, userAccountVo.getAreaCode(), Constant.CheckState.WIAT_SEND, Constant.CheckType.NEW, businessType);


        log.info("保存数据到中台");
//        sztCheck.tmpSendSZT(orderDTOList, userAccountVo.getAreaLevel());
        log.info("发送数据给核对中心");
        String checkMsg = scheduleCheckService.sendCheckInfo(checkList,Constant.BusinessCode.LINSHI,userAccountVo,Constant.CheckType.NEW);
        if(org.apache.commons.lang3.StringUtils.isNotBlank(checkMsg)){
            idcardCheckRstMsg.put("checkMsg",Arrays.asList(checkMsg));
        }

        List<String> successIdcardList = checkList.stream().map(CheckDTO::getIdcard).collect(Collectors.toList());
        idcardCheckRstMsg.put("success", successIdcardList);


        return idcardCheckRstMsg;
    }


    @Override
    public Map<String, List<String>> sendCheckCounty(List<CheckDTO> checkList, UserAccountVo userAccountVo, String businessType) {
        Map<String, List<String>> idcardCheckRstMsg = new HashMap<>();

        this.verifyNoCompleteCheck(checkList,idcardCheckRstMsg);
        if(CollectionUtils.isEmpty(checkList)){
            return idcardCheckRstMsg;
        }

        log.info("开始保存数据到check表");
        checkWriteService.addCheck(checkList, userAccountVo.getAreaCode(), Constant.CheckState.WIAT_SEND, Constant.CheckType.NEW, businessType);


        log.info("保存数据到中台");
//        sztCheck.tmpSendSZT(orderDTOList, userAccountVo.getAreaLevel());
        log.info("发送数据给核对中心");
        scheduleCheckService.sendCheckInfo(checkList,Constant.BusinessCode.LINSHI,userAccountVo,Constant.CheckType.NEW);

        List<String> successIdcardList = checkList.stream().map(CheckDTO::getIdcard).collect(Collectors.toList());
        idcardCheckRstMsg.put("success", successIdcardList);


        return idcardCheckRstMsg;
    }

    private List<String> verifyInfComp(List<CheckDTO> checkList,Map<String, List<String>> idcardCheckRstMsg){

        List<String> familyIds =  checkList.stream().map(c->c.getFamilyId()).collect(Collectors.toList());

        List<String> uniqueMaster = tmpFamilyMemberReadService.getUniqueMaster(familyIds);

        List<String> notUniqueMaster = familyIds.stream().filter(c->!uniqueMaster.contains(c)).collect(Collectors.toList());
        if(CollectionUtils.isNotEmpty(notUniqueMaster)){

            familyIds.removeAll(notUniqueMaster);
            List<String> notUniMasterIdCard =  checkList.stream().filter(c->notUniqueMaster.contains(c.getFamilyId())).map(c->c.getApplyIdcard()).collect(Collectors.toList());

            idcardCheckRstMsg.put("imperfectInfo",notUniMasterIdCard);
        }
        if(CollectionUtils.isEmpty(familyIds)){
            return familyIds;
        }

        List<String> noCompleteId = tmpFamilyMemberReadService.cntCompleteMemberInfo(familyIds);
        if(CollectionUtils.isNotEmpty(noCompleteId)){

            familyIds.removeAll(noCompleteId);
            List<String> noCompleteIdCard =  checkList.stream().filter(c->noCompleteId.contains(c.getFamilyId())).map(c->c.getIdcard()).collect(Collectors.toList());

            idcardCheckRstMsg.put("noCompleteMember",noCompleteIdCard);
            if(CollectionUtils.isEmpty(familyIds)){
                return familyIds;
            }
        }
        List<String> orderIds =  checkList.stream().map(c->c.getOrderId()).collect(Collectors.toList());


        List<String> nocertFamilyId =  tmpOrderCertReadService.selectFamilyTmpMustCerts(familyIds,orderIds);
        if(CollectionUtils.isNotEmpty(nocertFamilyId)){
            familyIds.removeAll(nocertFamilyId);

            List<String> noCertFamilyIdcard =  checkList.stream().filter(c->nocertFamilyId.contains(c.getFamilyId())).map(c->c.getIdcard()).collect(Collectors.toList());

            idcardCheckRstMsg.put("noExistCert",noCertFamilyIdcard);
            if(CollectionUtils.isEmpty(familyIds)){
                return familyIds;
            }
        }


        List<String> noIdCertFamilyId = tmpOrderCertReadService.selectNoIdcardCerts(familyIds,orderIds);
        if(CollectionUtils.isNotEmpty(noIdCertFamilyId)){

            familyIds.removeAll(noIdCertFamilyId);
            List<String> noIdCertFamilyIdcard =  checkList.stream().filter(c->noIdCertFamilyId.contains(c.getFamilyId())).map(c->c.getIdcard()).collect(Collectors.toList());

            idcardCheckRstMsg.put("noIdCertFamilyIdcard",noIdCertFamilyIdcard);
            if(CollectionUtils.isEmpty(familyIds)){
                return familyIds;
            }
        }


        List<String> noBackUpFamilyId = tmpFamilyMainReadService.selectNoBackUpFamilys(familyIds,orderIds);
        if(CollectionUtils.isNotEmpty(noBackUpFamilyId)){
            familyIds.removeAll(noBackUpFamilyId);
            List<String> noBackUpFamilyIdcard  =  checkList.stream().filter(c->noBackUpFamilyId.contains(c.getFamilyId())).map(c -> c.getIdcard()).collect(Collectors.toList());

            idcardCheckRstMsg.put("noBackUpFamilyIdcard",noBackUpFamilyIdcard);
        }
        return familyIds;
    }

    public void verifyNoCompleteCheck(List<CheckDTO> checkList, Map<String, List<String>> idcardCheckRstMsg){
        List<String> canNotSendCheckIdcardLsit = new ArrayList<>();


        List<String> familyIdList = checkList.stream().map(CheckDTO::getFamilyId).collect(Collectors.toList());


        List<String> noReportFamilyIdList = checkReadService.getNoCompleteFamilyId(familyIdList);


        if(noReportFamilyIdList.size() > 0){

            Map<String, CheckDTO> checkDTOMap = checkList.stream().collect(Collectors.toMap(c->c.getFamilyId(), c -> c));


            noReportFamilyIdList.forEach(familyId -> {
                checkList.remove(checkDTOMap.get(familyId));
                canNotSendCheckIdcardLsit.add(checkDTOMap.get(familyId).getIdcard());
            });


            idcardCheckRstMsg.put("canNotSendCheck", canNotSendCheckIdcardLsit);
        }
    }

    private List<CheckDTO> verifyOrderOfOther(List<CheckDTO> checkFileList, Map<String, List<String>> idcardCheckRstMsg) {

        List<String> idcardList = checkFileList.stream().map(CheckDTO::getIdcard).collect(Collectors.toList());

        List<FamilyMainHistoryDTO> familyHisByIdcard = familyMainHistoryReadService.getFamilyHisByIdcard(idcardList);
        List<String> canNotSendCheckIdcardList = new ArrayList<>();
        if (null != familyHisByIdcard && familyHisByIdcard.size() > 0) {
            List<String> familyIdList = familyHisByIdcard.stream().map(FamilyMainHistoryDTO::getId).collect(Collectors.toList());
            canNotSendCheckIdcardList = checkReadService.verifyFamilyIdCheck(familyIdList, idcardList, idcardCheckRstMsg);
        }

        List<String> finalStrings = new ArrayList<>();
        finalStrings.addAll(canNotSendCheckIdcardList);
        List<CheckDTO> needSendCheckList = checkFileList.stream().filter(
                checkDTO -> !finalStrings.contains(checkDTO.getIdcard())
        ).collect(Collectors.toList());
        return needSendCheckList;
    }


    private List<CheckDTO> verifyCert(List<CheckDTO> checkList, Map<String, List<String>> idcardCheckRstMsg) {

        List<String> notExitCertIdcardList = tmpOrderCertReadService.sendCheckVerifyFile(checkList);

        List<CheckDTO> needSendCheckList = checkList.stream().filter(checkDTO -> notExitCertIdcardList.contains(checkDTO.getIdcard()) == false).collect(Collectors.toList());

        if (notExitCertIdcardList.size() > 0) {
            idcardCheckRstMsg.put("noExistCert", notExitCertIdcardList);
        }

        return needSendCheckList;
    }


    private List<TmpOrderDTO> verifyOrderState(List<CheckDTO> checkList, OrderBizStateParam orderBizStateParam,
                                               Map<String, List<String>> idcardCheckRstMsg,
                                               UserAccountVo userAccountVo) {

        List<String> orderIdList = checkList.stream().map(CheckDTO::getOrderId).collect(Collectors.toList());


        orderBizStateParam.setOrderIdList(orderIdList);
        orderBizStateParam.setLtEqBizState(Constant.BizStateTmp.WAIT_APPROVE);
        orderBizStateParam.setGtEqBizState(Constant.BizStateTmp.SALVATION);
        if (Constant.UserLevel.COUNTY.equals(userAccountVo.getAreaLevel())) {

            orderBizStateParam.setLtEqBizState(Constant.BizStateTmp.COUNTY_WAIT_NOTICE_BOARD);
            orderBizStateParam.setGtEqBizState(Constant.BizStateTmp.APPROVE_ING);
        }

        List<TmpOrderDTO> needSendCheckOrderList = tmpOrderReadService.getOrderByIdAndBizStateCon(orderBizStateParam);

        if (needSendCheckOrderList.size() == orderIdList.size()) {

            return needSendCheckOrderList;
        }

        List<String> needSendCheckIdcardList = needSendCheckOrderList.stream().map(TmpOrderDTO::getIdcard).collect(Collectors.toList());

        List<String> canNotSendCheckIdcardLsit = checkList.stream()
                .filter(checkDTO -> needSendCheckIdcardList.contains(checkDTO.getIdcard()) == false)
                .map(CheckDTO::getIdcard)
                .collect(Collectors.toList());

        if(canNotSendCheckIdcardLsit.size() > 0){
            idcardCheckRstMsg.put("canNotSendCheck", canNotSendCheckIdcardLsit);
        }

        List<CheckDTO> tempCheckList = new ArrayList<>(checkList);
        for (CheckDTO dto : tempCheckList) {
            if (canNotSendCheckIdcardLsit.contains(dto.getIdcard())) {
                checkList.remove(dto);
            }
        }

        return needSendCheckOrderList;
    }


    private List<CheckDTO> verifyCheckReportFile(List<CheckDTO> checkList, Map<String, List<String>> idcardCheckRstMsg){
        List<String> familyIdList =  checkList.stream().map(CheckDTO::getFamilyId).collect(Collectors.toList());

        List<String> noReportFileIdcardList = checkReadService.getNoReportFile(familyIdList);
        if(CollectionUtils.isNotEmpty(noReportFileIdcardList)){
            idcardCheckRstMsg.put("noReport", noReportFileIdcardList);

            return checkList.stream().filter(checkDTO -> !noReportFileIdcardList.contains(checkDTO.getIdcard())).collect(Collectors.toList());
        }else{
            return checkList;
        }

    }


    @Override
    public String saveInHouseRecord(OrderInHouseDTO orderInHouse, List<String> orderCertIdList, UserAccountVo userAccountVo, String isUpOrder) {

        //this.isCanInHouse(orderInHouse.getOrderId());


        TmpOrderDTO orderDTO = tmpOrderReadService.getStateAndVersion(orderInHouse.getOrderId());

        if (Constant.UserLevel.COUNTY.equals(userAccountVo.getAreaLevel())) {

            if (Constant.BizStateTmp.COUNTY_WAIT_NOTICE_BOARD.equals(orderDTO.getBizState())) {
                throw new BizException(FailureCode.ERR_20061);
            }
        } else {
            if (Constant.BizStateTmp.WAIT_NOTICE_BOARD.equals(orderDTO.getBizState())) {
                throw new BizException(FailureCode.ERR_20061);
            }
        }

        OrderInHouseDTO orderInHouseDTO = inHouseReadService.queryNewByOrderId(orderInHouse.getOrderId(), userAccountVo.getAreaLevel());
        if ("0".equals(isUpOrder)) {
            if (null != orderInHouseDTO) {

                if ("0".equals(orderInHouseDTO.getState())) {
                    inHouseWriteService.updateById(orderInHouse, orderCertIdList, userAccountVo);
                } else {
                    throw new BizException("-1", "已发起过入户调查，不能再次发起");
                }
            } else {

                inHouseWriteService.addInHouse(orderInHouse, orderCertIdList, userAccountVo);

                String bizState = Constant.BizStateTmp.YES_IN_HOUSE_ING;
                if (Constant.UserLevel.COUNTY.equals(userAccountVo.getAreaLevel())) {

                    bizState = Constant.BizStateTmp.COUNTY_YES_IN_HOUSE_ING;
                }
                tmpOrderWriteService.updateOrderState(orderDTO, orderDTO.getBizState(), bizState);
            }
        }

        if ("1".equals(isUpOrder)) {

            if (Constant.UserLevel.STREET.equals(userAccountVo.getAreaLevel())
                    && !Constant.BizStateTmp.YES_IN_HOUSE_ING.equals(orderDTO.getBizState())) {
                throw new BizException("-1", "状态不是入户调查中，不能结束入户调查");
            } else if (Constant.UserLevel.COUNTY.equals(userAccountVo.getAreaLevel())
                    && !Constant.BizStateTmp.COUNTY_YES_IN_HOUSE_ING.equals(orderDTO.getBizState())) {
                throw new BizException("-1", "状态不是入户抽查中，不能结束入户抽查");
            }
            int i = tmpOrderCertReadService.queryCertIsExiten(new ArrayList<String>() {{
                add(orderInHouse.getOrderId());
            }}, "211", "3");
            if (i <= 0) {
                throw new BizException("-1", "没有上传入户调查证明材料，不能结束入户");
            }
            String bizState = Constant.BizStateTmp.YES_IN_HOUSE;
            if (Constant.UserLevel.COUNTY.equals(userAccountVo.getAreaLevel())) {

                bizState = Constant.BizStateTmp.COUNTY_YES_IN_HOUSE;
            }
            if (null != orderInHouseDTO) {
                orderInHouseDTO.setState("1");
                inHouseWriteService.updateById(orderInHouseDTO, orderCertIdList, userAccountVo);
            }
            tmpOrderWriteService.updateOrderState(orderDTO, orderDTO.getBizState(), bizState);
        }


        return orderInHouse.getId();
    }


    @Override
    public int isInHouse(String orderId, List<String> orderList, UserAccountVo userAccountVo) {

        OrderBizStateParam orderBizStateParam = new OrderBizStateParam();
        orderBizStateParam.setOrderId(orderId);
        orderBizStateParam.setOrderIdList(orderList);
        String bizState = Constant.BizStateTmp.YES_IN_HOUSE_ING;
        if (Constant.UserLevel.COUNTY.equals(userAccountVo.getAreaLevel())) {

            bizState = Constant.BizStateTmp.COUNTY_YES_IN_HOUSE_ING;
        }
        orderBizStateParam.setEqBizState(bizState);
        List<TmpOrderDTO> orderByIdAndBizStateCon = tmpOrderReadService.getOrderByIdAndBizStateCon(orderBizStateParam);
        if (CollectionUtils.isNotEmpty(orderByIdAndBizStateCon)) {
            if (CollectionUtils.isNotEmpty(orderList)) {
                return 0;
            } else {

                return 0;
            }
        } else {
            return 1;
        }
    }


    @Override
    public int modifyInHouseRecord(OrderInHouseDTO orderInHouse, List<String> orderCertIdList, UserAccountVo userAccountVo) {

        //this.isCanInHouse(orderInHouse.getOrderId());


        inHouseWriteService.updateById(orderInHouse, orderCertIdList, userAccountVo);



        return 1;
    }


    @Override
    public int isCanCalcFamilySalary(String orderId) {

        String bizState = tmpOrderReadService.getBizStateByBizStateRange(orderId, Constant.BizState.WAIT_NOTICE_BOARD);
        if (CommonUtil.invalidArgs(bizState)) {

            throw new BizException("-1", "未进行审核，无法计算待遇");
        }

        if (Constant.BizStateTmp.APPROVE_REJECT.equals(bizState) == false) {

            return 1;
        }








        return 1;
    }

    public void saveFirstAudit(TmpAuditDTO tmpAuditDTO, UserAccountVo userAccountVo){

        if("204".equals(tmpAuditDTO.getSalvType())){
            String standardMoney = standardReadDao.getStandardMoney(userAccountVo.getAreaCode().substring(0, 6) + "000000", "110","02");
            if(null != standardMoney){
                if(tmpAuditDTO.getSalvMoney()<Double.parseDouble(standardMoney)){
                    throw new BizException("-1","输入的救助金额最低不能低于农村标准");
                }
            }else{
                throw new BizException("-1","当前账号没有配置农村最低标准,请先配置标准");
            }
        }



        TmpOrderStateVerifyDTO orderStateVerifyDTO = tmpOrderReadService.getBizStateReportFile(tmpAuditDTO.getOrderId());
        ruleEngineReadService.getTempBizStateRuleThrow(Constant.TmpOrderBizStateType.START_FIRST_AUDIT,orderStateVerifyDTO,userAccountVo);


        tmpFamilyMemberWriteService.updateMemberIsSaveObject(tmpAuditDTO);
        if(tmpAuditDTO.getSalvMoney()!=null){

            tmpFamilySalaryWriteService.saveFamilySalary(tmpAuditDTO, userAccountVo);
        }


        tmpOrderDetailWriteService.saveFirstAuditOrderDetail(tmpAuditDTO, userAccountVo);


        TmpOrderEntity orderEntity = OrderConvert.convertOrder(tmpAuditDTO, orderStateVerifyDTO);
        tmpOrderWriteService.updateOrder(orderEntity);


        tmpFamilyMainWriteService.updateFamilyInfo(tmpAuditDTO, userAccountVo);

    }

    public void confirmFirstAudit(TmpAuditDTO tmpAuditDTO, UserAccountVo userAccountVo){

        if("204".equals(tmpAuditDTO.getSalvType())){
            String standardMoney = standardReadDao.getStandardMoney(userAccountVo.getAreaCode().substring(0, 6) + "000000", "110","02");
            if(null != standardMoney){
                if(tmpAuditDTO.getSalvMoney()<Double.parseDouble(standardMoney)){
                    throw new BizException("-1","输入的救助金额最低不能低于农村标准");
                }
            }else{
                throw new BizException("-1","当前账号没有配置农村最低标准,请先配置标准");
            }

        }
        tmpAuditDTO.setParentId(userAccountVo.getParentId());

        TmpOrderStateVerifyDTO orderStateVerifyDTO = tmpOrderReadService.getBizStateReportFile(tmpAuditDTO.getOrderId());
        ruleEngineReadService.getTempBizStateRuleThrow(Constant.TmpOrderBizStateType.COMPLETE_FIRST_AUDIT,orderStateVerifyDTO,userAccountVo);

        if(!CommonUtil.invalidArgs(tmpAuditDTO.getCheckResult()) && "1".equals(tmpAuditDTO.getCheckResult())){
            String nextActviti = activitiReadService.getNextStepForTmp(tmpAuditDTO);
            if(!CommonUtil.invalidArgs(nextActviti)){
                orderStateVerifyDTO.setNextBizState(nextActviti);

                if(!Constant.BizStateTmpNew.APPROVE_REJECT.equals(orderStateVerifyDTO.getState())){
                    orderStateVerifyDTO.setNextState(nextActviti);
                }
            }
        }

        tmpFamilyMemberWriteService.updateMemberIsSaveObject(tmpAuditDTO);
        if(tmpAuditDTO.getSalvMoney()!=null){

            tmpFamilySalaryWriteService.saveFamilySalary(tmpAuditDTO, userAccountVo);
        }


        tmpOrderDetailWriteService.saveFirstAuditOrderDetail(tmpAuditDTO, userAccountVo);


        TmpOrderEntity orderEntity = OrderConvert.convertOrder(tmpAuditDTO, orderStateVerifyDTO);
        tmpOrderWriteService.updateOrder(orderEntity);


        tmpFamilyMainWriteService.updateFamilyInfo(tmpAuditDTO, userAccountVo);

    }


    @Override
    public void saveSalvationAudit(TmpAuditDTO tmpAuditDTO, UserAccountVo userAccountVo) {

        if("204".equals(tmpAuditDTO.getSalvType())){
            String standardMoney = standardReadDao.getStandardMoney(userAccountVo.getAreaCode().substring(0, 6) + "000000", "110","02");
            if(null != standardMoney){
                if(tmpAuditDTO.getSalvMoney()<Double.parseDouble(standardMoney)){
                    throw new BizException("-1","输入的救助金额最低不能低于农村标准");
                }
            }else{
                throw new BizException("-1","当前账号没有配置农村最低标准,请先配置标准");
            }
        }


//        int rst = this.isInHouse(tmpAuditDTO.getOrderId(), null, userAccountVo);




        TmpOrderStateVerifyDTO orderStateVerifyDTO = tmpOrderReadService.getBizStateReportFile(tmpAuditDTO.getOrderId());
        ruleEngineReadService.getTempBizStateRuleThrow(Constant.TmpOrderBizStateType.START_TOWN_AUDIT,orderStateVerifyDTO,userAccountVo);


        tmpFamilyMemberWriteService.updateMemberIsSaveObject(tmpAuditDTO);

        if(tmpAuditDTO.getSalvMoney()!=null){

            tmpFamilySalaryWriteService.saveFamilySalary(tmpAuditDTO, userAccountVo);
        }



        tmpOrderDetailWriteService.saveAuditOrderDetail(tmpAuditDTO, userAccountVo);


        TmpOrderEntity orderEntity = OrderConvert.convertOrder(tmpAuditDTO, orderStateVerifyDTO);
        tmpOrderWriteService.updateOrder(orderEntity);


        tmpFamilyMainWriteService.updateFamilyInfo(tmpAuditDTO, userAccountVo);

    }



    public void judgmentDate(String rescueyears,String orderId){
        if(StringUtils.isEmpty(rescueyears)){
            throw  new BizException("-1","救助年月不能为空");
        }


        SimpleDateFormat sdf  =new SimpleDateFormat("yyyyMM");
        try {
            Date dateD = sdf.parse(rescueyears);
            String todayD = sdf.format(new Date());
            Date todayF= sdf.parse(todayD);
            if(dateD.getTime() < todayF.getTime()){
                throw  new BizException("-1","登记救助年月小于当前年月，请重新选择救助年月");
            }
        } catch (ParseException e1) {
            e1.printStackTrace();
        }


    }


    @Override
    public String submitSalvationRequest(TmpAuditDTO tmpAuditDTO, UserAccountVo userAccountVo) {
        if(Constant.AudtiOrApprovalResult.YES.equals(tmpAuditDTO.getCheckResult())){

            this.judgmentDate(tmpAuditDTO.getRescueyears(),tmpAuditDTO.getOrderId());
        }



        if("204".equals(tmpAuditDTO.getSalvType())){
            String standardMoney = standardReadDao.getStandardMoney(userAccountVo.getAreaCode().substring(0, 6) + "000000", "110","02");
            if(null != standardMoney){
                if(tmpAuditDTO.getSalvMoney()<Double.parseDouble(standardMoney)){
                    throw new BizException("-1","输入的救助金额最低不能低于农村标准");
                }
            }else{
                throw new BizException("-1","当前账号没有配置农村最低标准,请先配置标准");
            }
        }

        TmpOrderStateVerifyDTO orderStateVerifyDTO = tmpOrderReadService.getBizStateReportFile(tmpAuditDTO.getOrderId());
        orderStateVerifyDTO.setNextCondition(tmpAuditDTO.getCheckResult());
        ruleEngineReadService.getTempBizStateRuleThrow(Constant.TmpOrderBizStateType.COMPLETE_TOWN_AUDIT,orderStateVerifyDTO,userAccountVo);

        if(!CommonUtil.invalidArgs(tmpAuditDTO.getCheckResult()) && "1".equals(tmpAuditDTO.getCheckResult())) {
            String standardMoneys = standardReadDao.getStandardMoney(userAccountVo.getAreaCode().substring(0, 6) + "000000", "500", "500");
            Double standardMoney;
            if (null != standardMoneys) {
                standardMoney = Double.parseDouble(standardMoneys);
                double familySendMoney = tmpAuditDTO.getSalvMoney();
                if (familySendMoney > standardMoney) {
                    throw new BizException("-1", "救助金额大于乡镇审核限额，无法办结");
                }

            } else {
                throw new BizException("-1", "当前账号没有配置审批限额标准,请先配置标准");
            }
        }


        tmpFamilyMemberWriteService.updateMemberIsSaveObject(tmpAuditDTO);

        if(tmpAuditDTO.getSalvMoney()!=null){

            tmpFamilySalaryWriteService.saveFamilySalary(tmpAuditDTO, userAccountVo);
        }


        tmpOrderDetailWriteService.saveAuditOrderDetail(tmpAuditDTO, userAccountVo);


        TmpOrderEntity orderEntity = OrderConvert.convertOrder(tmpAuditDTO, orderStateVerifyDTO);
        orderEntity.setCheckDate(new Date());
        orderEntity.setFinishLevel(userAccountVo.getAreaLevel());
        tmpOrderWriteService.updateOrder(orderEntity);

        if(Constant.BizStateNew.APPROVE_REJECT.equals(orderStateVerifyDTO.getNextState())){

            return "";
        }

        tmpFamilyMainWriteService.updateFamilyInfo(tmpAuditDTO, userAccountVo);

        TmpOrderDTO orderDTO = tmpOrderReadService.getOrderAndFamily(Arrays.asList(tmpAuditDTO.getOrderId())).get(0);
        tmpFamilyMainHistoryWriteService.backHistory(orderDTO,orderDTO.getFamilyId(), userAccountVo);

//        if(Constant.PayWay.BANK.equals(tmpAuditDTO.getPayWay())||Constant.AudtiOrApprovalResult.YES.equals(tmpAuditDTO.getCheckResult())){


        String remindBankInfo = "";
        if("1".equals(tmpAuditDTO.getCheckResult())) {
//            remindBankInfo = this.remindBankInfo(orderStateVerifyDTO.getFamilyId(),tmpAuditDTO.getBusinessType());


            log.info("开始完善临时救助申请人的银行卡信息");
            remindBankInfo = generateBankInfo(orderDTO);
            log.info("临时救助申请人的银行卡信息完善完成");
        }

        if(!Constant.AudtiOrApprovalResult.REJECT.equals(tmpAuditDTO.getCheckResult())){
            scheduleCheckService.sendApproveResult(Arrays.asList(tmpAuditDTO.getOrderId()),Constant.BusinessCode.LINSHI,userAccountVo);
        }

        if(Constant.AudtiOrApprovalResult.YES.equals(tmpAuditDTO.getCheckResult())){
            Map<String,Object> map = new HashMap<>();
            map.put("operateType", "1");
            map.put("businessType", Constant.BusinessCode.LINSHI);
            map.put("orderId", tmpAuditDTO.getOrderId());
            map.put("yearMon", "");
            map.put("areaCode", "");
        }

        return remindBankInfo;
    }


    private String generateBankInfo(TmpOrderDTO orderDTO) {
        TmpFamilyMemberEntity applyMemberInfo = tmpFamilyMemberReadService.getByIdCard(orderDTO.getApplyIdcard());
        if (applyMemberInfo == null)
            throw new RuntimeException("未查询到申请人的基础信息，请联系管理员");
//        BankEntity bankEntity = bankReadService.getBankByFamilyId(orderDTO.getFamilyId(),applyMemberInfo.getId(), Constant.BusinessCode.LINSHI);
        List<BankEntity> bankEntity = bankReadService.getBankByApplyIdCardAndBizType(orderDTO.getApplyIdcard(), Constant.BusinessCode.LINSHI);
        if (bankEntity.isEmpty()) {
            BankEntity bkObj = TmpBankInfoConvert.convertToBankEntity(orderDTO, applyMemberInfo.getId());
            int rst = bankWriteService.insertIgnoreNull(bkObj);
            if (rst != 1) {
                throw new RuntimeException("申请人银行卡信息生成失败");
            }
            log.info("临时救助申请人的银行卡基础信息生成完成毕");
            return "未录入银行卡信息";
        }
        return "";
    }

    public String remindBankInfo(String familyID,String businessType){
        List<BankEntity> list = bankReadService.getBankByfamilyId(familyID,businessType);
        if(!list.isEmpty()){
            String master = list.get(0).getMasterAccount();
            String agent = list.get(0).getAgentAccount();
            if(org.apache.commons.lang3.StringUtils.isEmpty(master) && org.apache.commons.lang3.StringUtils.isEmpty(agent)){
                return "未录入银行卡信息";
            }

        }else{
            return "未录入银行卡信息";
        }
        return "";
    }



    @Override
    public TmpAuditDTO calcFamilySalaryBySalvationRule(TmpAuditDTO tmpAuditDTO, UserAccountVo userAccountVo) {

        tmpFamilySalaryWriteService.packageCalcSalaryParam(tmpAuditDTO);


        tmpFamilySalaryWriteService.calcSalaryBySalvationRule(userAccountVo, tmpAuditDTO);


        tmpFamilySalaryWriteService.getOnethingCheckType(userAccountVo, tmpAuditDTO);


        return tmpAuditDTO;
    }

    @Override
    public TmpAuditDTO getFirstSalvationAudit(String familyId, String orderId) {

        TmpAuditDTO tmpAuditDTO = tmpFamilySalaryReadService.getFirstAuditSalaryByOrderId(orderId);
        tmpAuditDTO = CommonUtil.invalidArgs(tmpAuditDTO) ? new TmpAuditDTO() : tmpAuditDTO;

        if (!CommonUtil.invalidArgs(tmpAuditDTO.getKinds())) {
            List<GoodsDTO> goodsDTOList = JSONObject.parseArray(tmpAuditDTO.getKinds(), GoodsDTO.class);
            tmpAuditDTO.setGoodsList(goodsDTOList);
        }


        List<TmpFamilyMemberDTO> memberList = tmpFamilyMemberReadService.getByFamilyId(familyId, null);
        tmpAuditDTO.setMemberList(memberList);


        TmpOrderStateVerifyDTO orderStateVerifyDTO = tmpOrderReadService.getBizStateReportFile(orderId);
        if(!Constant.BizStateTmpNew.AUDIT_ING.equals(orderStateVerifyDTO.getBizState())){
            tmpAuditDTO.setOrderDetailId(null);
            tmpAuditDTO.setCheckDate(null);
            tmpAuditDTO.setCheckOpinion(null);
            tmpAuditDTO.setCheckPeople(null);
            tmpAuditDTO.setCheckResult(null);
        }

        return tmpAuditDTO;
    }


    @Override
    public TmpAuditDTO getFirstSalvationAudits(String familyId, String orderId,String mainReason) {

        TmpAuditDTO tmpAuditDTO = tmpFamilySalaryReadService.getFirstAuditSalaryByOrderId(orderId);
        tmpAuditDTO = CommonUtil.invalidArgs(tmpAuditDTO) ? new TmpAuditDTO() : tmpAuditDTO;

        if (!CommonUtil.invalidArgs(tmpAuditDTO.getKinds())) {
            List<GoodsDTO> goodsDTOList = JSONObject.parseArray(tmpAuditDTO.getKinds(), GoodsDTO.class);
            tmpAuditDTO.setGoodsList(goodsDTOList);
        }


        String year = DateUtil.format(new Date(), "yyyy");
        DateTime dateTime = DateUtil.parse(year, "yyyy");

        String beginOfYear = DateUtil.beginOfYear(dateTime).toString("yyyyMM");

        String endOfYear = DateUtil.endOfYear(dateTime).toString("yyyyMM");

        TmpFamilyMainEntity tmpFamilyMainEntity = tmpFamilyMainReadService.getById(familyId);
        if(tmpFamilyMainEntity != null){
            mainReason = tmpFamilyMainEntity.getMainReason();
        }

        TmpOrderEntity tempOrderDTO = tmpOrderReadService.getById(orderId);

        List<TmpFamilyMemberDTO> memberList = tmpFamilyMemberReadService.getByFamilyIdAndReason(familyId,mainReason,beginOfYear,endOfYear);
        for (TmpFamilyMemberDTO obj : memberList) {
            if (tempOrderDTO.getApplyIdcard().equals(obj.getIdcard())) {
                obj.setIsSaveObject("1");
                obj.setIsApply("1");
            }
        }
        tmpAuditDTO.setMemberList(memberList);


        TmpOrderStateVerifyDTO orderStateVerifyDTO = tmpOrderReadService.getBizStateReportFile(orderId);
        if(!Constant.BizStateTmpNew.AUDIT_ING.equals(orderStateVerifyDTO.getBizState())){
            tmpAuditDTO.setOrderDetailId(null);
            tmpAuditDTO.setCheckDate(null);
            tmpAuditDTO.setCheckOpinion(null);
            tmpAuditDTO.setCheckPeople(null);
            tmpAuditDTO.setCheckResult(null);
        }
        tmpAuditDTO.setCurrDate(DateUtil.format(new Date(), "yyyy-MM-dd"));
        return tmpAuditDTO;
    }

    @Override
    public TmpAuditDTO getSalvationAudit(String familyId, String orderId) {

        TmpAuditDTO tmpAuditDTO = tmpFamilySalaryReadService.getAuditSalaryByOrderId(orderId);
        tmpAuditDTO = CommonUtil.invalidArgs(tmpAuditDTO) ? new TmpAuditDTO() : tmpAuditDTO;

        if (!CommonUtil.invalidArgs(tmpAuditDTO.getKinds())) {
            List<GoodsDTO> goodsDTOList = JSONObject.parseArray(tmpAuditDTO.getKinds(), GoodsDTO.class);
            tmpAuditDTO.setGoodsList(goodsDTOList);
        }


        List<TmpFamilyMemberDTO> memberList = tmpFamilyMemberReadService.getByFamilyId(familyId, null);

        tmpAuditDTO.setMemberList(memberList);

        return tmpAuditDTO;
    }


    @Override
    public TmpAuditDTO getSalvationAudits(String familyId, String orderId,String mainReason) {

        TmpAuditDTO tmpAuditDTO = tmpFamilySalaryReadService.getAuditSalaryByOrderId(orderId);
        tmpAuditDTO = CommonUtil.invalidArgs(tmpAuditDTO) ? new TmpAuditDTO() : tmpAuditDTO;

        if (!CommonUtil.invalidArgs(tmpAuditDTO.getKinds())) {
            List<GoodsDTO> goodsDTOList = JSONObject.parseArray(tmpAuditDTO.getKinds(), GoodsDTO.class);
            tmpAuditDTO.setGoodsList(goodsDTOList);
        }


        String year = DateUtil.format(new Date(), "yyyy");
        DateTime dateTime = DateUtil.parse(year, "yyyy");

        String beginOfYear = DateUtil.beginOfYear(dateTime).toString("yyyyMM");

        String endOfYear = DateUtil.endOfYear(dateTime).toString("yyyyMM");

        List<TmpFamilyMemberDTO> memberList = tmpFamilyMemberReadService.getByFamilyIdAndReason(familyId,mainReason,beginOfYear,endOfYear);

        TmpOrderEntity tempOrderDTO = tmpOrderReadService.getById(orderId);
        for (TmpFamilyMemberDTO obj : memberList) {
            if (tempOrderDTO.getApplyIdcard().equals(obj.getIdcard())) {
                obj.setIsSaveObject("1");
                obj.setIsApply("1");
            }
        }
        tmpAuditDTO.setMemberList(memberList);
        tmpAuditDTO.setCurrDate(DateUtil.format(new Date(), "yyyy-MM-dd"));
        return tmpAuditDTO;
    }



    private OrderBizStateParam getBizStateRule(String orderId, List<String> orderIdList, String bizStateType) {
        OrderBizStateParam orderBizStateParam = new OrderBizStateParam(orderId, orderIdList, bizStateType);
        Facts facts = new Facts();
        facts.put("orderBizStateParam", orderBizStateParam);
        ruleEngineTemplate.fire("orderBizStateRules", facts);
        return orderBizStateParam;
    }


    @Override
    public Map<String, List<String>> issueOrder(List<String> orderIdList, List<String> idcardAllList) {

        Map<String, List<String>> map = new HashMap<>();
        List<TmpOrderDTO> orderRecordFlag = tmpOrderReadService.getOrderRecordFlag(orderIdList, Constant.OrderRecordFlag.COUNTY);
        List<String> idcardList = orderRecordFlag.stream().map(TmpOrderDTO::getIdcard).collect(Collectors.toList());
        if (CollectionUtils.isNotEmpty(orderRecordFlag)) {
            if (orderRecordFlag.size() == orderIdList.size()) {

                int i = tmpOrderWriteService.updateRecordFlagById(orderIdList, Constant.OrderRecordFlag.DOWN);
                if (i <= 0) {
                    throw new BizException("-1", "数据下发异常，请联系管理员");
                }
            } else {

                List<String> collect = idcardList.stream().filter(idcard -> idcardList.contains(idcard) == false).collect(Collectors.toList());
                map.put("noExist", collect);

                List<String> ids = orderRecordFlag.stream().map(TmpOrderDTO::getId).collect(Collectors.toList());
                int i = tmpOrderWriteService.updateRecordFlagById(ids, Constant.OrderRecordFlag.DOWN);
                if (i <= 0) {
                    throw new BizException("-1", "数据下发异常，请联系管理员");
                }
            }
        } else {

            map.put("noExist", idcardAllList);
        }

        return map;
    }


    @Override
    public TmpApprovalDTO getApproval(String familyId, String orderId) {

        TmpApprovalDTO tmpApprovalDTO = tmpFamilySalaryReadService.getApprovalSalaryByOrderId(orderId);
        tmpApprovalDTO = CommonUtil.invalidArgs(tmpApprovalDTO) ? new TmpApprovalDTO() : tmpApprovalDTO;

        String bizState = tmpOrderReadService.getBizStateById(orderId);
        if(Constant.BizStateTmpNew.APPROVE_SAVE.equals(bizState)){
            TmpOrderDetailEntity orderDetailEntity = tmpOrderDetailReadService.selectLastApproval(orderId);
            if(!CommonUtil.invalidArgs(orderDetailEntity)){
                tmpApprovalDTO.setOrderDetailId(orderDetailEntity.getId());
                tmpApprovalDTO.setCheckOpinion(orderDetailEntity.getCheckOpinion());
                tmpApprovalDTO.setCheckResult(orderDetailEntity.getCheckResult());
            }
        }

        if (!CommonUtil.invalidArgs(tmpApprovalDTO.getKinds())) {
            List<GoodsDTO> goodsDTOList = JSONObject.parseArray(tmpApprovalDTO.getKinds(), GoodsDTO.class);
            tmpApprovalDTO.setGoodsList(goodsDTOList);
        }


        List<TemMemberAndSalaryDTO> memberList = tmpMemberSalaryReadService.getMemberListByFamilyId(orderId, familyId);

        tmpApprovalDTO.setMemberList(memberList);
        tmpApprovalDTO.setCurrDate(DateUtil.format(new Date(), "yyyy-MM-dd"));
        return tmpApprovalDTO;
    }



    @Override
    public void saveApproval(TmpOrderDetailEntity orderDetailEntity, UserAccountVo userAccountVo) {

        if("204".equals(orderDetailEntity.getSalvType())){
            TmpOrderEntity updateOrderEntity = new TmpOrderEntity();

            TmpOrderDTO orderDTO = tmpOrderReadService.getOrderAndFamily(new ArrayList<String>() {{
                add(orderDetailEntity.getOrderId());
            }}).get(0);
            if(Double.doubleToLongBits(orderDTO.getSalvMoney()) != Double.doubleToLongBits(orderDetailEntity.getSalvMoney())){
                updateOrderEntity.setSalvMoney(orderDetailEntity.getSalvMoney());
                updateOrderEntity.setOnethingCheckType(orderDetailEntity.getOnethingCheckType());
                updateOrderEntity.setId(orderDetailEntity.getOrderId());
                tmpOrderWriteService.updateOrder(updateOrderEntity);
            }
        }



        tmpOrderDetailWriteService.saveApprovalOrderDetail(orderDetailEntity, userAccountVo);

        TmpOrderStateVerifyDTO orderStateVerifyDTO = tmpOrderReadService.getBizStateReportFile(orderDetailEntity.getOrderId());
        ruleEngineReadService.getTempBizStateRuleThrow(Constant.TmpOrderBizStateType.START_COUNTY_APPROVE,orderStateVerifyDTO,userAccountVo);
        tmpOrderWriteService.updateOrderState(orderStateVerifyDTO);
    }











//        TmpOrderStateVerifyDTO orderStateVerifyDTO = tmpOrderReadService.getBizStateReportFile(orderDetailEntity.getOrderId());
//        orderStateVerifyDTO.setNextCondition(orderDetailEntity.getCheckResult());
//        ruleEngineReadService.getTempBizStateRuleThrow(Constant.TmpOrderBizStateType.COMPLETE_COUNTY_APPROVE,orderStateVerifyDTO,userAccountVo);









//        if(Constant.AudtiOrApprovalResult.YES.equals(orderDetailEntity.getCheckResult())
//                && Constant.OneThingCheckType.YES.equals(orderDTO.getOnethingCheckType())){











//        updateOrderEntity.setId(orderDetailEntity.getOrderId());
//        updateOrderEntity.setBizState(orderStateVerifyDTO.getNextBizState());

//        updateOrderEntity.setState(orderStateVerifyDTO.getNextState());
//        updateOrderEntity.setFinishLevel(userAccountVo.getAreaLevel());


//        tmpFamilyMainHistoryWriteService.backHistory(orderDTO,orderDTO.getFamilyId(), userAccountVo);

//        if(Constant.PayWay.BANK.equals(orderDTO.getPayWay())||Constant.AudtiOrApprovalResult.YES.equals(orderDetailEntity.getCheckResult())){





    public void judgmentTreatment(String rescueyears,String orderId){
        TmpFamilySalaryEntity tmpFamilySalaryEntity = new TmpFamilySalaryEntity();
        tmpFamilySalaryEntity.setOrderId(orderId);
        tmpFamilySalaryEntity.setStartDate(rescueyears);
        tmpFamilySalaryEntity.setEndDate(rescueyears);
        tmpFamilySalaryWriteService.updateIgnoreNullByOrderId(tmpFamilySalaryEntity);

        TmpMemberSalaryEntity tmpMemberSalaryEntity = new TmpMemberSalaryEntity();
        tmpMemberSalaryEntity.setOrderId(orderId);
        tmpMemberSalaryEntity.setStartDate(rescueyears);
        tmpMemberSalaryEntity.setEndDate(rescueyears);
        tmpMemberSalaryWriteService.updateIgnoreNullByOrderId(tmpMemberSalaryEntity);

    }



    @Override
    public String confirmApproval(TmpOrderDetailEntity orderDetailEntity, UserAccountVo userAccountVo) {

        TmpOrderEntity updateOrderEntity = new TmpOrderEntity();

        if(Constant.AudtiOrApprovalResult.YES.equals(orderDetailEntity.getCheckResult())){


            this.judgmentDate(orderDetailEntity.getRescueyears(),orderDetailEntity.getOrderId());

            this.judgmentTreatment(orderDetailEntity.getRescueyears(),orderDetailEntity.getOrderId());
            updateOrderEntity.setStartMonth(orderDetailEntity.getRescueyears());
            updateOrderEntity.setEndMonth(orderDetailEntity.getRescueyears());
        }



        TmpOrderStateVerifyDTO orderStateVerifyDTO = tmpOrderReadService.getBizStateReportFile(orderDetailEntity.getOrderId());
        orderStateVerifyDTO.setNextCondition(orderDetailEntity.getCheckResult());
        ruleEngineReadService.getTempBizStateRuleThrow(Constant.TmpOrderBizStateType.COMPLETE_COUNTY_APPROVE,orderStateVerifyDTO,userAccountVo);

        tmpOrderDetailWriteService.saveApprovalOrderDetail(orderDetailEntity, userAccountVo);


        TmpOrderDTO orderDTO = tmpOrderReadService.getOrderAndFamily(new ArrayList<String>() {{
            add(orderDetailEntity.getOrderId());
        }}).get(0);
        String onethingCheckType = orderDTO.getOnethingCheckType();



        if("204".equals(orderDetailEntity.getSalvType()) && "01".equals(orderDetailEntity.getPayWay())){
            String standardMoney = standardReadDao.getStandardMoney(userAccountVo.getAreaCode().substring(0, 6) + "000000", "110","02");
            if(null != standardMoney){
                if(orderDetailEntity.getSalvMoney()<Double.parseDouble(standardMoney)){
                    throw new BizException("-1","输入的救助金额最低不能低于农村标准");
                }
            }else{
                throw new BizException("-1","当前账号没有配置农村最低标准,请先配置标准");
            }

            TmpApprovalDTO tmpApprovalDTO = tmpFamilySalaryReadService.getFamilySalaryByOrderId(orderDetailEntity.getOrderId());


//            Double.doubleToLongBits(orderDTO.getSalvMoney()) == Double.doubleToLongBits(orderDetailEntity.getSalvMoney())
            if(Double.doubleToLongBits(tmpApprovalDTO.getSalvMoney()) != Double.doubleToLongBits(orderDetailEntity.getSalvMoney())){
                updateOrderEntity.setSalvMoney(orderDetailEntity.getSalvMoney());
                updateOrderEntity.setOnethingCheckType(orderDetailEntity.getOnethingCheckType());
                onethingCheckType = orderDetailEntity.getOnethingCheckType();
                TmpAuditDTO tmpAuditDTO = new TmpAuditDTO();
                tmpAuditDTO.setOrderId(orderDetailEntity.getOrderId());
                tmpAuditDTO.setPayWay(orderDetailEntity.getPayWay());
                tmpAuditDTO.setSalvType(orderDetailEntity.getSalvType());
                tmpAuditDTO.setSalvMoney(orderDetailEntity.getSalvMoney());
                tmpAuditDTO.setBusinessType(Constant.BusinessCode.LINSHI);
                tmpAuditDTO.setRescueyears(orderDetailEntity.getRescueyears());
                tmpAuditDTO.setSaveMemberNumber(orderDetailEntity.getSaveMemberNumber());
                tmpFamilySalaryWriteService.saveFamilySalary(tmpAuditDTO, userAccountVo);

            }
        }

        if(Constant.AudtiOrApprovalResult.YES.equals(orderDetailEntity.getCheckResult())
                && Constant.OneThingCheckType.YES.equals(onethingCheckType)){

            int i = tmpOrderCertReadService.queryCertIsExiten(new ArrayList<String>(new ArrayList<String>() {{
                add(orderDTO.getOrderId());
            }}), "215", "1");
            if(i <= 0){
                throw new BizException("-1","请上传一事一议证明材料");
            }
        }

        updateOrderEntity.setId(orderDetailEntity.getOrderId());
        updateOrderEntity.setBizState(orderStateVerifyDTO.getNextBizState());
        updateOrderEntity.setCheckDate(new Date());
        updateOrderEntity.setState(orderStateVerifyDTO.getNextState());
        updateOrderEntity.setFinishLevel(userAccountVo.getAreaLevel());
        tmpOrderWriteService.updateOrder(updateOrderEntity);
        if(Constant.BizStateTmpNew.APPROVE_REJECT.equals(orderStateVerifyDTO.getNextState())){

            return "";
        }

        tmpFamilyMainHistoryWriteService.backHistory(orderDTO,orderDTO.getFamilyId(), userAccountVo);

//        if(Constant.PayWay.BANK.equals(orderDTO.getPayWay())||Constant.AudtiOrApprovalResult.YES.equals(orderDetailEntity.getCheckResult())){


        String remindBankInfo = "";
        if("1".equals(orderDetailEntity.getCheckResult())) {
//            remindBankInfo = this.remindBankInfo(orderStateVerifyDTO.getFamilyId(),orderDetailEntity.getBusinessType());


            log.info("开始完善临时救助申请人的银行卡信息");
            remindBankInfo = generateBankInfo(orderDTO);
            log.info("临时救助申请人的银行卡信息完善完成");
        }

        if(!Constant.AudtiOrApprovalResult.REJECT.equals(orderDetailEntity.getCheckResult())){
            scheduleCheckService.sendApproveResult(Arrays.asList(orderDetailEntity.getOrderId()),Constant.BusinessCode.LINSHI,userAccountVo);
        }

        if(Constant.AudtiOrApprovalResult.YES.equals(orderDetailEntity.getCheckResult())){
            Map<String,Object> map = new HashMap<>();
            map.put("operateType", "1");
            map.put("businessType", Constant.BusinessCode.LINSHI);
            map.put("orderId", orderDetailEntity.getOrderId());
            map.put("yearMon", "");
            map.put("areaCode", "");
        }

        return remindBankInfo;
    }


    @Override
    public Map<String, List<String>> exceBatchReport(List<String> orderIdList, UserAccountVo userAccountVo) {
        Map<String, List<String>> idcardCheckRstMsg = new HashMap<>();

        List<TmpOrderDTO> stateAndVersions = tmpOrderReadService.getOrderAndFamily(orderIdList);

        List<TmpOrderDTO> canOrderList = new ArrayList<>();

        List<String> notIdcardList = stateAndVersions.stream().filter(order -> {
            if (Constant.BizStateTmp.CONFIRM_APPROVE.equals(order.getBizState())) {
                canOrderList.add(order);
                return false;
            } else {
                return true;
            }
        }).map(TmpOrderDTO::getIdcard).collect(Collectors.toList());
        if (CollectionUtils.isNotEmpty(notIdcardList)) {
            idcardCheckRstMsg.put("noExistState", notIdcardList);
        }

        if (CollectionUtils.isNotEmpty(canOrderList)) {
            for (TmpOrderDTO order : canOrderList) {
                ActivitiParam activitiParam = ActivitiConvert.convertActivitiParam(order);
                activitiParam.setBusinessType("500");
                activitiParam.setNextCondition("1");
                String nextActviti = activitiReadService.getOrderNextActviti(activitiParam, userAccountVo.getRoles());

                if (StringUtils.isEmpty(nextActviti)) {
                    notIdcardList.add(order.getIdcard());
                } else {

                    TmpOrderEntity updateOrderEntity = new TmpOrderEntity();
                    updateOrderEntity.setId(order.getOrderId());
                    updateOrderEntity.setState(nextActviti);
                    updateOrderEntity.setBizState(nextActviti);
                    tmpOrderWriteService.updateOrder(updateOrderEntity);
                }
            }
        }
        return idcardCheckRstMsg;
    }


    @Override
    public BaseResult<Boolean> cancelSalvationRequestTown(String orderId) {
        BaseResult<Boolean> rstMsg = new BaseResult<>();
        rstMsg.setData(true);
        rstMsg.setMsg("撤销成功");



        TmpOrderEntity orderEntity = tmpOrderReadService.getById(orderId);
        if (null != orderEntity) {
//            if (Integer.parseInt(Constant.BizStateTmp.WAIT_APPROVE) <= Integer.parseInt(orderEntity.getBizState())) {
            if (Integer.parseInt(Constant.BizStateTmp.APPROVE_REJECT) <= Integer.parseInt(orderEntity.getBizState()) ||
                    Integer.parseInt(Constant.BizStateTmp.TOWN_CHECK) == Integer.parseInt(orderEntity.getBizState()) ||
                    Integer.parseInt(orderEntity.getBizState()) == Integer.parseInt("22")) {
                TaDictPo codeCache = dictionaryReadService.getCodeCache(DictConstant.BIZSTATETEMP, orderEntity.getBizState());
                throw new BizException("-1", "家庭【" + orderEntity.getIdcard() + "】当前业务状态为" + codeCache.getLabel() + "，不能操作删除");
            }
        }

        inHouseWriteService.deleteByOrderId(orderId);


        TmpOrderDetailEntity tmpOrderDetail = new TmpOrderDetailEntity();
        tmpOrderDetail.setOrderId(orderId);
        tmpOrderDetailWriteService.delete(tmpOrderDetail);


        tmpFamilySalaryWriteService.deleteSalaryByOrderId(orderId);


        OrderStateEntity updateOrderEntity = new OrderStateEntity();
        updateOrderEntity.setOrderId(orderId);
        updateOrderEntity.setState(Constant.BizStateTmp.TOWN_DELETE);
        updateOrderEntity.setBizState(Constant.BizStateTmp.TOWN_DELETE);

        int rst = tmpOrderWriteService.updateState(updateOrderEntity);
        if (rst <= 0) {
            rstMsg.setData(false);
            rstMsg.setMsg("操作异常，撤销失败");
        }

        return rstMsg;
    }


    @Override
    public Map<String, List<String>> cancelSalvationRequestTowns(List<String> orderIdList, UserAccountVo userAccountVo) {
        Map<String, List<String>> idcardCheckRstMsg = new HashMap<>();
        List<String> notStateIdcardList = new ArrayList<>();


        List<TmpOrderEntity> orderEntitys = tmpOrderReadService.getByOrderIds(orderIdList);
        orderEntitys.forEach(orderEntity -> {
            if (null != orderEntity) {
                if (Integer.parseInt(Constant.BizStateTmp.YES_IN_HOUSE) < Integer.parseInt(orderEntity.getBizState()) ||
                        Integer.parseInt(Constant.BizStateTmp.TOWN_CHECK) == Integer.parseInt(orderEntity.getBizState())) {
                    notStateIdcardList.add(orderEntity.getIdcard());

                }else{

                    inHouseWriteService.deleteByOrderId(orderEntity.getId());

                    TmpOrderDetailEntity tmpOrderDetail = new TmpOrderDetailEntity();
                    tmpOrderDetail.setOrderId(orderEntity.getId());
                    tmpOrderDetailWriteService.delete(tmpOrderDetail);

                    tmpFamilySalaryWriteService.deleteSalaryByOrderId(orderEntity.getId());

                    OrderStateEntity updateOrderEntity = new OrderStateEntity();
                    updateOrderEntity.setOrderId(orderEntity.getId());
                    updateOrderEntity.setState(Constant.BizStateTmp.TOWN_DELETE);
                    updateOrderEntity.setBizState(Constant.BizStateTmp.TOWN_DELETE);

                    tmpOrderWriteService.updateState(updateOrderEntity);

//                    this.deleteBankInfo(orderEntity.getFamilyId(), Constant.BusinessCode.LINSHI);

                    this.deleteApplyBankInfo(orderEntity.getApplyIdcard(),Constant.BusinessCode.LINSHI);
                }
            }

        });
        if (CollectionUtils.isNotEmpty(notStateIdcardList)) {
            idcardCheckRstMsg.put("noExistState", notStateIdcardList);
        }

        return idcardCheckRstMsg;
    }


    private void deleteApplyBankInfo(String applyIdCard, String businessType) {

        List<BankEntity> bankEntityList = bankReadService.getBankByApplyIdCardAndBizType(applyIdCard, businessType);
        if(!CollectionUtils.isEmpty(bankEntityList)) {
            for (BankEntity entity : bankEntityList                 ) {
                bankWriteService.deleteBankInfo(entity.getId());
            }
        }
    }


    public void deleteBankInfo(String familyId, String businessType){

        List<BankEntity> bankEntityList = bankReadService.getBankByfamilyId(familyId,businessType);
        if(!CollectionUtils.isEmpty(bankEntityList)) {
            bankWriteService.deleteBankInfo(bankEntityList.get(0).getId());
        }
    }


    @Override
    public String isCanAuditOrApproval(String orderId, String familyId, String curBizState, UserAccountVo userAccountVo) {

        int rst = tmpFamilyMemberReadService.cntInfoComplete(familyId);
        if(rst > 0){
            throw new BizException("-1", "成员信息未完成无法审核，请先完善成员的信息");
        }
        int i = this.getcertCount(familyId);
        if(i <= 0){
            return "没有临时救助申请书，不能发起审核";
        }


        OrderBizStateParam orderBizStateParam = new OrderBizStateParam();
        orderBizStateParam.setOrderId(orderId);

        String notEqBizState = Constant.BizStateTmp.YES_IN_HOUSE_ING;
        String ltEqBizState = Constant.BizStateTmp.WAIT_APPROVE;

        if (Constant.UserLevel.COUNTY.equals(userAccountVo.getAreaLevel())) {

            notEqBizState = Constant.BizStateTmp.COUNTY_YES_IN_HOUSE_ING;
            ltEqBizState = Constant.BizStateTmp.APPROVE_SAVE;
        }
        orderBizStateParam.setNotEqBizState(notEqBizState);
        orderBizStateParam.setLtEqBizState(ltEqBizState);
        List<TmpOrderDTO> orderByIdAndBizStateCon = tmpOrderReadService.getOrderByIdAndBizStateCon(orderBizStateParam);
        if(orderByIdAndBizStateCon.size() <= 0){
            TaDictPo taDictPo = dictionaryReadService.getCodeCache(DictConstant.BIZSTATETEMP, curBizState);

            return taDictPo.getLabel() + ",不可以被审核";
        }
        return "";
    }


    @Override
    public void isCanApprove(String orderId,String familyId,UserAccountVo userAccountVo){









        TmpOrderStateVerifyDTO orderStateVerifyDTO = tmpOrderReadService.getBizStateReportFile(orderId);
        ruleEngineReadService.getTempBizStateRuleThrow(Constant.OrderBizStateType.START_COUNTY_APPROVE, orderStateVerifyDTO, userAccountVo);
    }

    private int getcertCount(String familyId){

        ReferenceParam referenceParam = new ReferenceParam();
        referenceParam.setFileType("201");
        referenceParam.setAssociationTable("1");
        referenceParam.setAssociationTableId(familyId);
        List<Map<String, String>> listMap = tmpOrderCertReadService.listByType(referenceParam);
        if(CollectionUtils.isNotEmpty(listMap)){
            return 1;
        }
        return 0;
    }


    @Override
    public void isCanFirstAudit(String orderId,String familyId,UserAccountVo userAccountVo){


        tempSalvationApplyService.cntFamilyMaster(familyId);

        tempSalvationApplyService.cntCompleteInfoNum(familyId);

        tempSalvationApplyService.verifyTmpCert(orderId,familyId);

        tempSalvationApplyService.verifyBackUpHtml(orderId);

        TmpOrderStateVerifyDTO orderStateVerifyDTO = tmpOrderReadService.getBizStateReportFile(orderId);
        ruleEngineReadService.getTempBizStateRuleThrow(Constant.TmpOrderBizStateType.START_FIRST_AUDIT,orderStateVerifyDTO,userAccountVo);
    }

    @Override
    public void isCanSalvationAudit(String orderId,String familyId,UserAccountVo userAccountVo){

        TmpOrderStateVerifyDTO orderStateVerifyDTO = tmpOrderReadService.getBizStateReportFile(orderId);
        ruleEngineReadService.getTempBizStateRuleThrow(Constant.TmpOrderBizStateType.START_TOWN_AUDIT,orderStateVerifyDTO,userAccountVo);
    }

    @Override
    public void isCanInHouse(String orderId, UserAccountVo userAccountVo) {

        List<String> idCardList = tmpOrderReadService.cntFileObjId(Arrays.asList(orderId));
        if(idCardList!=null&&idCardList.size()>0){
            throw new BizException(FailureCode.ERR_20084);
        }

        TmpOrderStateVerifyDTO tmpOrderStateVerifyDTO = tmpOrderReadService.getBizStateReportFile(orderId);


        String bizStateType = Constant.UserLevel.STREET.equals(userAccountVo.getAreaLevel())
                ? Constant.OrderBizStateType.START_TOWN_IN_HOUSE
                : Constant.OrderBizStateType.START_TOWN_IN_HOUS_COUNTY;


        ruleEngineReadService.getTempBizStateRuleThrow(bizStateType, tmpOrderStateVerifyDTO, userAccountVo);
    }

    @Override
    public void isCanUploadCheckFile(String familyId,String orderId){


        tempSalvationApplyService.cntFamilyMaster(familyId);

        tempSalvationApplyService.cntCompleteInfoNum(familyId);

        tempSalvationApplyService.verifyExpireCheck(orderId);
    }

    @Override
    public int chengeMemberSaveObject(String orderId,String familyId,String memberId,String type,String isMaster){
        TmpFamilyMemberEntity member = new TmpFamilyMemberEntity();
        member.setId(memberId);
        member.setIsSaveObject(type);
        tmpFamilyMemberWriteService.updateFamilyMember(member);

        TmpFamilyMainEntity family = new TmpFamilyMainEntity();
        family.setId(familyId);
        String change = "";
        if("0".equals(type)){
            if("01".equals(isMaster)){
                family.setMasterInSave("02");
            }
            change = "down";
        }else{
            if("01".equals(isMaster)){
                family.setMasterInSave("01");
            }
            change = "up";
        }
        int i = tmpFamilyMainWriteService.changeSaveMemberById(family,change);
        if(i <= 0){
            throw new BizException("-1", "修改家庭保障对象异常");
        }
         i = tmpOrderWriteService.changeSaveMember(orderId, change);
        if(i <= 0){
            throw new BizException("-1", "修改业务保障对象异常");
        }
        return i;
    }

    @Override
    public int uploadCheckFile(MultipartFile[] files, String orderId,String reason, String areaCode){

        if(files==null||files.length<1){
            throw new BizException("-1","没有核对文件");
        }
        int res = 0;
        try{
            String [] keys = new String[files.length];
            int i = 0;
            for(MultipartFile file:files) {
                if(!file.getOriginalFilename().endsWith("pdf") && !file.getOriginalFilename().endsWith("PDF") && !file.getOriginalFilename().endsWith("fdf")){
                    throw new BizException("-1","请上传PDF格式核对报告");
                }
                String objectkey = fileService.upload(file.getInputStream(), file.getOriginalFilename());
                keys[i] = objectkey;
                i++;
            }
            TmpOrderEntity orderEntity = tmpOrderReadService.getById(orderId);
            CheckEntity check  = new CheckEntity();
            String batchNo = BatchNoUtil.getBatch(Constant.BusiCode.CHECK_BATCH, areaCode);
            check.setCheckResultState(Constant.CheckResultState.SUCCESS);
            check.setOrderId(orderId);
            check.setAreaCode(areaCode);
            check.setFamilyId(orderEntity.getFamilyId());
            check.setIdcard(orderEntity.getIdcard());
            check.setStandType(Constant.BusinessStandType.LINGSHI);
            check.setBusinessType(Constant.BusinessCode.LINSHI);
            check.setCheckBatchNo(batchNo);
            check.setCheckRemark(reason);
            res = checkWriteService.uploadCheckFile(check,keys);
        }catch(IOException e){
            e.printStackTrace();
            log.error("核对文件上传失败");
            throw new BizException(FailureCode.ERR_20078);
        }
        return res;
    }


    @Override
    public ExcelInfo exportExcelSave(TemporaryOrderParam param, UserAccountVo accountVo){
        ExcelInfo excelInfo = null;
        QueryParamUtil.setBaseParamValue(param,accountVo);
        param.setBusinessType(Constant.BusinessCode.LINSHI);
        if("1".equals(param.getExportType())){



            List<TmpOrderExcelPendingDTO> list = tmpOrderReadService.exportTownSalvation(param);
            excelInfo = exportExcelService.exportOrgOpLogs(TmpOrderExcelPendingDTO.class,list,"临时救助乡镇待办信息.xls",
                    "临时救助乡镇待办列表","临时救助乡镇待办列表",false);
        }else if("2".equals(param.getExportType())){

            List<TmpOrderExcelPendingCDTO> list = tmpOrderReadService.exportTownSalvationCounty(param);
            excelInfo = exportExcelService.exportOrgOpLogs(TmpOrderExcelPendingCDTO.class,list,"临时救助区县待办信息.xls",
                    "临时救助区县待办列表","临时救助区县待办列表",false);
        }


        return excelInfo;
    }


    @Override
    public void sendBackSys(String orderId, String content, UserAccountVo userAccountVo, String businessType){

        OrderStateEntity orderStateEntity = new OrderStateEntity();
        orderStateEntity.setOrderId(orderId);
        orderStateEntity.setState(Constant.BizStateNew.SYS_BACK);
        orderStateEntity.setBizState(Constant.BizStateNew.SYS_BACK);
        orderStateEntity.setBackContent(content);
        tmpOrderWriteService.updateState(orderStateEntity);


    }

    @Override
    public void deleteSelectRecord(String orderId) {
        int i = tmpOrderWriteService.deleteRecordById(orderId);
    }
}
